package com.wt.test.proxy;

import org.springframework.aop.TargetSource;

/**
 * @description
 * @author: wangtao
 * @date:17:24 2019/3/4
 * @email:taow02@jumei.com
 */
public class CustomTargetSource implements TargetSource {

	private ITask task1;

	private ITask task2;

	private int counter = 0;

	public CustomTargetSource() {
	}

	public CustomTargetSource(ITask task1, ITask task2) {
		this.task1 = task1;
		this.task2 = task2;
	}

	@Override
	public Class<?> getTargetClass() {
		return ITask.class;
	}

	/**
	 * 表明是否要返回同一个目标对象实例，singletonTargetSource该方法返回false
	 * @return
	 */
	@Override
	public boolean isStatic() {
		return false;
	}

	@Override
	public Object getTarget() throws Exception {
		//如果counter是单数就返回task1否则返回task2
		return counter++ % 2 == 1 ? task1 : task2;
	}

	/**
	 * 如果isStatic返回false，就会释放当前目标对象，即不返回同一个目标对象，但是是否需要释放还得代码说了算，这里就不写代码释放对象了，等GC回收，通常该方法不用事先
	 * @param target
	 * @throws Exception
	 */
	@Override
	public void releaseTarget(Object target) throws Exception {

	}
}
